package com.example.llh.zyfypt_110llh.model.tware;


import com.example.llh.zyfypt_110llh.bean.tware.TwareBean;
import com.example.llh.zyfypt_110llh.iface.tware.TwareListener;
import com.example.llh.zyfypt_110llh.iface.tware.Twareiface;
import com.example.llh.zyfypt_110llh.service.tware.TwareService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by BYS on 2017/4/28.
 */
//Model是retrofit联网获取数据的四个步骤
public class TwareModel implements Twareiface {
    private Retrofit retrofit;
    private String BASEURL="http://amicool.neusoft.edu.cn/";//网址前半部分
    //构造函数
    public TwareModel(){
        //   retrofit第一步，生成retrofit对象
        retrofit=new Retrofit.Builder()
                .baseUrl(BASEURL)//给定网址
                .addConverterFactory(GsonConverterFactory.create())//指定转换方式
                .build();//build出来
    }
    //获取文章数据
    @Override
    //           实现回调，articleListener将他回调到fragment当中。getResultList实际是Articleiface中未实现的方法
    public void getResultList(String tware, int page, String sessionID, final TwareListener twareListener) {
        //使用Retrofit-2，实例化Service
        TwareService twareService=retrofit.create(TwareService.class);
        //使用Retrofit-3，发送网络数据请求
        Call<List<TwareBean>> call
                =twareService.getResult(tware,page,sessionID);
        //把请求加入队列，结果通过Callback回调返回
        call.enqueue(new Callback<List<TwareBean>>() {
            @Override
            public void onResponse(Call<List<TwareBean>> call, Response<List<TwareBean>> response) {
                if(response.isSuccessful()&&response!=null){
                    twareListener.onResponse(response.body());
                }
                else
                    twareListener.onFail("onresponse fail");
            }

            @Override
            public void onFailure(Call<List<TwareBean>> call, Throwable t) {
                twareListener.onFail(t.toString());
            }
        });
    }
}
